package Invalid;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import java.util.*;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class SSLServer {
	
	private SSLServerSocket sslServerSocket = null;
	private InetAddress currentIp;
	private ServerControl myControl;
	private String password;
	
	public SSLServer( int port , String pass )
	{
		// Save the password of the current server.
		this.password = pass;
		// Get current IP address and show it in the screen.
		getIp();
		// Create server control
		//myControl = new ServerControl();
		
		listenTo( port );
		runServer();

	}
	
	private void listenTo( int port )
	{
		SSLServerSocketFactory mySSLServerSocketFactory = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
		// Listen to a certain
		try 
		{
			sslServerSocket = (SSLServerSocket)mySSLServerSocketFactory.createServerSocket( port );
        } 
		catch (IOException e) 
		{
        	System.err.println("Could not listen on port: " + port );
            System.exit(1);
        }
		System.out.println("Successfully listen on port: " + port );
	}
	
	private void getIp()
	{
		try 
		{
			currentIp = InetAddress.getLocalHost();
			System.out.println("Current IP address : " + currentIp.getHostAddress());
		} 
		catch (UnknownHostException e) 
		{
 			e.printStackTrace();
 		}
	}

	private void runServer()  {
		System.out.println("Server runs successfully!");
		SSLSocket clientSocket = null;
		try
		{
			clientSocket = (SSLSocket)sslServerSocket.accept();	
		}
		catch( Exception e)
		{
			System.err.println("Can not hear from a client");
			e.printStackTrace();
		}
		if( clientSocket != null )
		{
			 System.out.println( "A clinent is connected!" );
		}
		try{
        	InputStream inStream = clientSocket.getInputStream();
        	OutputStream outStream = clientSocket.getOutputStream();
        	Scanner in = new Scanner( inStream );
        	PrintWriter out =  new PrintWriter(outStream, true );
        	this.myControl = new ServerControl(inStream, outStream);
        	Thread controlThread = new Thread(this.myControl);
        	controlThread.start();
	        while( clientSocket != null )
	        {
	        	Thread.sleep( 1000 );
	        	out.println("Hello world!");
	        }
		}
		catch(Exception e)
		{
			
		}
	}
	
}
